<?php
declare (strict_types = 1);

namespace app\common\model;
use think\facade\Db;

class PracticeAnswer extends Base
{

    protected $name = 'practice_answer';
    /**
     * 提交试卷
     */
    public static function submit($param,$user)
    {
        try {
            $info = Practice::where(['uid' => $user->id])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '暂无练习试卷'];
            }
            if ($info['status'] != 1) {
                return ['code' => -1, 'msg' => '试卷已提交'];
            }
            parent::destroy(['practice_id' => $info['id']], true);
            $data = $param['data'];
            // print('<pre>');print_r($data);die;
            $list=[];
            foreach ($data as $key => $value) {
                $type = Exam::where(['id'=>$value['id']])->value('types');
                $list[]=[
                    'uid'=>$user->id,
                    'exam_id'=>$value['id'],
                    'practice_id'=>$info['id'],
                    'answer'=>$value['answer'],
                    'score'=>$type == 1?$info['radio_score']:$info['check_score'],
                    'types'=>self::judge($value['id'],$value['answer']),
                    'create_time' => time(),
                    'update_time' => time(),
                ];
            }
            if(!empty($list)){
                parent::insertAll($list);
            }
            $score = parent::where(['uid'=>$user->id,'types'=>1,'practice_id'=>$info['id']])->sum('score');
            $info->score = $score;
            $info->status = 2;
            $info->save();
            return ['code' => 1, 'msg' => '提交成功！'];
        }catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 判断对错
     */
    public static function judge($id,$my_answer)
    {
        $answer = Exam::where(['id'=>$id])->value('answer');
        return $answer==$my_answer?1:2;
    }
}
